//
//  ViewController.swift
//  QQ
//
//  Created by zhang on 16/1/7.
//  Copyright © 2016年 jin. All rights reserved.
//

import UIKit

class ViewController: UIViewController,UITableViewDataSource,UITableViewDelegate,UITextFieldDelegate {
    lazy var messageFrames:[MessageFrame] = MessageFrame.instanceWithFile()
    @IBOutlet var sendMessageView: UIView!
    @IBOutlet weak var tableView: UITableView!
    override func viewDidLoad() {
        super.viewDidLoad()
        //去掉cell的分割线
        self.tableView.separatorStyle = UITableViewCellSeparatorStyle.None
        self.tableView.allowsSelection = false
        //设置背景色
        self.tableView.backgroundColor = UIColor(red: 125/255, green: 125/255, blue: 125/255, alpha: 1)
        // Do any additional setup after loading the view, typically from a nib.
        //订阅键盘位置改变的通知,注意，有订阅就要有退订
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardChange:", name: UIKeyboardWillChangeFrameNotification, object: nil)
    }
    //在析构方法中退订通知
    deinit
    {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
        //
    }
    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 1
    }
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.messageFrames.count
    }
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = MessageCell.instanceWithTableView(self.tableView)
        cell.messageFrame = self.messageFrames[indexPath.row]
        return cell
    }
    func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        return self.messageFrames[indexPath.row].cellHeight
    }
    func tableView(tableView: UITableView, willSelectRowAtIndexPath indexPath: NSIndexPath) -> NSIndexPath? {
        return nil
    }
    // table代理方法
    func scrollViewDidScroll(scrollView: UIScrollView) {
        self.view.endEditing(true)
    }
    func keyboardChange(not:NSNotification)
    {
        //键盘位置没有发生变化的时候的位置信息，注意这里的转换
//        let beginRect = not.userInfo!["UIKeyboardFrameEndUserInfoKey"]!.CGRectValue
        //也可以直接取得，不过是一个可选类型
        let beginRect = not.userInfo![UIKeyboardFrameEndUserInfoKey]!.CGRectValue
        //键盘位置没有发生变化后的位置信息
        let endRect = not.userInfo!["UIKeyboardFrameBeginUserInfoKey"]!.CGRectValue
        let y = beginRect.origin.y - endRect.origin.y
        //动画效果，注意这里的类型转换
        UIView.animateWithDuration(NSTimeInterval(not.userInfo![UIKeyboardAnimationDurationUserInfoKey]!.floatValue), animations: {
            self.view.transform = CGAffineTransformTranslate(self.view.transform, 0, y)
        })
    }
    //文章本框键盘发送方法
    func textFieldShouldReturn(textField: UITextField) -> Bool {
        self.sendMessage(textField.text!, type: 0)
        //使用dispatch延时发送恢复消息
        let minseconds = 2 * Double(NSEC_PER_SEC)
        let dtime = dispatch_time(DISPATCH_TIME_NOW, Int64(minseconds))
        dispatch_after(dtime, dispatch_get_main_queue(), {
            self.sendMessage("哈哈哈",type: 1)
        })
        return true
    }
    //发送消息
    func sendMessage(text:NSString,type:NSNumber)
    {
        //初始化信息数据
        let message = Message()
        message.text = text
        message.type = type
        //获取时间
        let data = NSDate()
        let dataFormat = NSDateFormatter()
        dataFormat.dateFormat = "HH:mm"
        message.time = dataFormat.stringFromDate(data)
        //判断是否显示时间 lable
        if message.time.isEqualToString((self.messageFrames.last?.message.time)! as String)
        {
            message.hiddenTime = false
        }
        //添加进数据来源数组
        self.messageFrames.append(MessageFrame.init(message: message))
        //获得消息的 indexPath
        let indexPath = NSIndexPath(forRow: self.messageFrames.count - 1, inSection: 0)
        //插入cell
        self.tableView.insertRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Fade)
        //动画效果
        UIView.animateWithDuration(2, animations: {
            //滚动到当前发送的信息位置
            self.tableView.scrollToRowAtIndexPath(indexPath, atScrollPosition: UITableViewScrollPosition.Bottom, animated: true)
        })
        
    }
}

